import styles from './index.module.scss'
import { NavBar, Form, Input, List, Button, Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router'
import { LoginForm } from '@/types/data'
import { useDispatch } from 'react-redux'
import { loginAction, smsAction } from '@/store/actions/login'
import { useEffect, useRef, useState } from 'react'
import { InputRef } from 'antd-mobile/es/components/input'

// 定时器id 根据提示 设置定时器id的类型
let interId: NodeJS.Timeout

export default function Login() {
  // 倒计时时间的hook
  const [timeLeft, setTimeLeft] = useState(0)
  const history = useHistory()
  const dispatch = useDispatch()
  const location = useLocation<{ from: string }>()
  console.log('location:', location)
  // Form的hook
  const [form] = Form.useForm()
  // 手机号输入框的 ref
  const inputRef = useRef<InputRef>(null)

  // 校验通过
  const onFinish = async (value: LoginForm) => {
    await dispatch(loginAction(value))
    // 能走到这里 说明是ok
    Toast.show({
      icon: 'success',
      content: '登录成功',
      duration: 300,
      afterClose() {
        if (location.state?.from) {
          // 有来源地址
          history.push(location.state?.from)
        } else {
          // 跳转页面
          history.push('/')
        }
      },
    })
  }
  // 校验失败
  const onFinishFailed = () => {
    console.log('onFinishFailed')
  }

  // 获取验证码
  const getCode = async () => {
    // 倒计时时间改为60
    setTimeLeft((timeLeft) => 60)
    interId = setInterval(function () {
      setTimeLeft((timeLeft) => {
        // 方法2 在 setXXhook的第一个参数中 获取上一次的修改结果
        if (timeLeft === 0) {
          clearInterval(interId)
          return 0
        }
        return timeLeft - 1
      })
    }, 1000)
    try {
      const res = await form.validateFields(['mobile'])
      const mobile = res.mobile
      dispatch(smsAction(mobile))
    } catch (error) {
      // console.dir(error)
      // 手机号输入框获取焦点
      inputRef.current?.focus()
    }
  }

  // 检测timeLeft的值 在钩子,结合 依赖timeLeft
  // useEffect(() => {
  //   console.log('timeLeft:', timeLeft)
  // }, [timeLeft])

  // 清除定时器
  useEffect(() => {
    return () => {
      clearInterval(interId)
    }
  }, [])

  return (
    <div className={styles.root}>
      {/* 导航 */}
      <NavBar onBack={() => history.go(-1)}></NavBar>

      {/* 表单 */}
      <div className='login-form'>
        <h2 className='title'>账号登录</h2>
        <Form form={form} initialValues={{ mobile: '13911111111', code: '246810' }} onFinish={onFinish} onFinishFailed={onFinishFailed}>
          <Form.Item
            name='mobile'
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '手机号格式有误' },
            ]}
            className='login-item'
          >
            <Input ref={inputRef} placeholder='请输入手机号'></Input>
          </Form.Item>
          <List.Item
            className='login-code-extra'
            extra={
              <span onClick={timeLeft === 0 ? getCode : undefined} className='code-extra'>
                {timeLeft === 0 ? '发送验证码' : `还有${timeLeft}S`}
              </span>
            }
          >
            <Form.Item
              name='code'
              rules={[
                { required: true, message: '请输入验证码' },
                { pattern: /^\d{6}$/, message: '验证码6个数字' },
              ]}
              className='login-item'
            >
              <Input placeholder='请输入验证码'></Input>
            </Form.Item>
          </List.Item>
          <Form.Item>
            <Button type='submit' color='primary' block className='login-submit'>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
